//
//  FavoritesViewController.swift
//  AntProj
//
//  Created by 陈宇 on 2017/5/2.
//  Copyright © 2017年 🐜. All rights reserved.
//

import UIKit
import PullToRefresh
import Haneke
import SwifterSwift

enum ListingType {
    case posted
    case favorite
    case reviewed
}

fileprivate let reviewedDataKey = "reviewedDataKey"

class ListingController: BaseTableViewController<House> {
    
    var type: ListingType = .posted

    override var tableStyle: UITableViewStyle {
        return .grouped
    }
    
    override var topRefreshable: Bool {
        return self.type != .reviewed
    }
    
    override func configureLeftItem() {
        addLeftBarButtonWithImage(#imageLiteral(resourceName: "menu"))
    }
    
    convenience init(_ type: ListingType) {
        self.init()
        self.type = type
    }
    
    override func configureUI() {
        super.configureUI()
        
        tableView.register(nib: UINib(nibName: "HouseCell", bundle: nil), withCellClass: HouseCell.self)
        tableView.separatorStyle = .none
        tableView.rowHeight = 100
        tableView.hideEmpty()
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: HouseCell.self)!
        cell.house = dataSource[indexPath.section][indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 5 : 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 5
    }
    
    override func configureEvent() {
        if self.type == .reviewed {
            Shared.dataCache.fetch(key: reviewedDataKey).onSuccess({ (data) in
                guard let houses = NSKeyedUnarchiver.unarchiveObject(with: data) as? [House] else { return }
                self.dataSource.append(contentsOf: houses.map { [$0] })
                self.tableView.reloadData()
            })
        } else {
            refreshData()
        }
    }
    
    func refreshData(_ position: Position = .top) {
        let req: RestFullAPI?
        switch self.type {
        case .posted:
            req = .PostedHouses
        case .favorite:
            req = .FavoriteHouses
        default:
            req = nil
        }
        
        guard let request = req else { return }
        
        api.request(request).unWrapper().mapArray(type: House.self).subscribe(onNext: { (houses) in
            self.dataSource.append(contentsOf: houses.map { [$0] })
            self.tableView.reloadData {
                self.tableView.endRefreshing(at: position)
            }
        }, onError: { _ in
            self.tableView.endRefreshing(at: position)
        }).addDisposableTo(disposeBag)
    }
    
    override func refreshing(_ position: Position) {
        switch position {
        case .top:
            dataSource.removeAll()
            refreshData()
        case .bottom:
            refreshData(.bottom)
        }
    }
    

}
